package com.moyun.zbmy.youxian.ui.fragment;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.youxian.beans.CityServiceBean;
import com.moyun.zbmy.youxian.beans.MallJsonVo;
import com.moyun.zbmy.youxian.beans.ServiceCityListVo;
import com.moyun.zbmy.youxian.beans.ServiceConfigBean;
import com.moyun.zbmy.youxian.ui.activities.CommodityDetailActivity;
import com.moyun.zbmy.youxian.ui.activities.IntegralStoreActivity;
import com.moyun.zbmy.youxian.ui.activities.ServiceH5Activity;
import com.moyun.zbmy.youxian.ui.activities.TYFOH5Activity;
import com.moyun.zbmy.youxian.ui.widget.MyWebChromeClient;
import com.moyun.zbmy.youxian.utils.UserManager;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.moyun.zbmy.youxian.R;
import com.moyun.zbmy.youxian.application.Cache;
import com.moyun.zbmy.youxian.base.BaseFragment;
import com.moyun.zbmy.youxian.beans.ServiceBean;
import com.moyun.zbmy.youxian.beans.ServiceDataBean;
import com.moyun.zbmy.youxian.beans.ServiceVo;
import com.moyun.zbmy.youxian.http.AbsNetCallBack;
import com.moyun.zbmy.youxian.http.NetUtils;
import com.moyun.zbmy.youxian.ui.activities.H5NormalActivity;
import com.moyun.zbmy.youxian.ui.activities.LoginActivity;
import com.moyun.zbmy.youxian.ui.adapter.ServicePagerAdapter;
import com.moyun.zbmy.youxian.ui.adapter.ServiceRecentlyUsedServiceAdapter;
import com.moyun.zbmy.youxian.utils.GaoDeLocationUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * 服务   我要办
 */
public class ServiceFragment extends BaseFragment {
    private static final int TO_EXCHANGE_CITY = 1;
    private static final int CODE_REQUEST_LOGIN = 2;
    private String serviceUrl = "";
    public static final String configUrl = "/sctv/appConfig.json";
    @BindView(R.id.service_web)
    protected WebView webView;
    @BindView(R.id.load_error)
    protected LinearLayout webViewError;
    @BindView(R.id.error_str)
    protected CustomFontTextView errorText;
    private long refreshTime = 0;//上一次刷新数据的时间
    private boolean isLoadSuccess = true;
    private boolean isLoadFinish = false;
    private String token;
    private List<CityServiceBean> stateList = new ArrayList<>();
    private CityServiceBean localCityBean;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_service, container, false);
        ButterKnife.bind(this, view);
        Cache.getInstance().setCurrentChannelId("");
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initWebView();
        getServiceConfig();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            Cache.getInstance().setCurrentChannelId("");
        } else {
            if (System.currentTimeMillis() - refreshTime > 3 * 60 * 1000) {
                getServiceConfig();
            }
        }

    }


    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }

    /**
     * 获取后台配置的服务数据
     */

    private void getServiceConfig() {
        refreshTime = System.currentTimeMillis();
        NetUtils.getNetAdapter().getServiceConfigData(getOwnerName(), configUrl, new AbsNetCallBack<ServiceConfigBean>(ServiceConfigBean.class) {
            @Override
            public void onSuc(ServiceConfigBean config) {
                if (null != config) {
                    getCityList(config.getUrl());
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    private void getCityList(String url) {
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(getContext(), "数据错误", Toast.LENGTH_LONG).show();
            return;
        }
//        cityUrl = url;
        NetUtils.getNetAdapter().getServiceCityList(getOwnerName(), url, new AbsNetCallBack<ServiceCityListVo>(ServiceCityListVo.class) {
            @Override
            public void onSuc(ServiceCityListVo vo) {
                if (null != vo.getListInfo()) {
                    Cache.getInstance().setServiceCityList(vo.getListInfo());
                    if (null != vo.getListInfo() && vo.getListInfo().size() > 0) {
                        serviceUrl = vo.getListInfo().get(0).getCityH5Url();
                        initWebView();
                    }
                } else {
                    webViewError.setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    errorText.setText("未配置相关数据");
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                webViewError.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
                errorText.setText("加载失败");
            }
        });
    }

    private void initWebView() {
        webView.setWebChromeClient(new MyWebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
//                super.onGeolocationPermissionsShowPrompt(origin, callback);
                final boolean remember = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(ServiceFragment.this.getContext());
                builder.setTitle("位置信息");
                builder.setMessage("允许获取您的地理位置信息吗？").setCancelable(true).setPositiveButton("允许",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                callback.invoke(origin, true, remember);
                            }
                        })
                        .setNegativeButton("不允许",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        callback.invoke(origin, false, false);
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                Log.i("test", "openFileChooser 3");
//                IntegralStoreActivity.this.uploadFile = uploadFile;
//                openFileChooseProcess(null);
            }

        });
        webView.setWebViewClient(new WebViewClient() {


            //加载错误的时候会回调
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(view, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
                    if (!isLoadFinish) {
                        webViewError.setVisibility(View.VISIBLE);
                        webView.setVisibility(View.GONE);
                        isLoadSuccess = false;
                    }
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                // 在这里显示自定义错误页
                if (!isLoadFinish) {
                    webViewError.setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    isLoadSuccess = false;
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 在这里显示自定义错误页
                if (!isLoadFinish) {
                    webViewError.setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    isLoadSuccess = false;
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                isLoadSuccess = true;
                isLoadFinish = false;
            }

            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String titleStr = view.getTitle();
                if (!TextUtils.isEmpty(titleStr)) {
//                    if (TextUtils.isEmpty(title)){
//                    title = titleStr;
//                    }
                }
                if (isLoadSuccess && webView.getProgress() == 100) {
                    webViewError.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    isLoadFinish = true;
                }
            }
        });
        webView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void callRouter(String s1, String s2) {
                //H5页面调用Android原生代码
                if (!TextUtils.isEmpty(s1)) {
                    try {
                        JLog.e("htmlLogin", "-----------------------s1-" + s1 + "----s2" + s2);
                        JSONObject jso = new JSONObject(s1);
                        MallJsonVo jsonBean = new Gson().fromJson(s1, MallJsonVo.class);
                        parseJSMethod(jsonBean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "bridge");
        WebSettings settings = webView.getSettings();
        // 使用缓存
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + " SCGC_UA");
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false);//垂直不显示
        settings.setDomStorageEnabled(true);
//        settings.getUserAgentString()
        //使h5页面适应手机屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //设置可以支持缩放
        settings.setSupportZoom(true);
        //设置出现缩放工具
        settings.setBuiltInZoomControls(true);
        //隐藏缩放工具
        settings.setDisplayZoomControls(false);
        //允许地理位置可用
        settings.setGeolocationEnabled(true);
        //扩大比例的缩放
        settings.setUseWideViewPort(true);
        // 支持JavaScript
        settings.setJavaScriptEnabled(true);
//        settings.setMediaPlaybackRequiresUserGesture(false);
        loadWeb();
    }

    private void loadWeb() {
        String url = serviceUrl;
        if (UserManager.isLoginS()) {
            token = UserManager.getInstance().getToken();
        }
        if (!TextUtils.isEmpty(url)) {
            errorText.setText("加载失败");
            isLoadSuccess = true;
            if (!TextUtils.isEmpty(token)) {
                if (!url.contains("?")) {
                    webView.loadUrl(url + "?token=" + token);
                } else {
                    webView.loadUrl(url + "&token=" + token);
                }
            } else {
                webView.loadUrl(url);
            }
        }
    }

    /**
     * 回调的方法解析判断
     */
    protected void parseJSMethod(MallJsonVo jsonBean) {
        String method = jsonBean.getMethod().trim();
        if ("detailJson".equalsIgnoreCase(method)) {
            //商品详情
            if (null != UserManager.getInstance().getUser()) {
                String url = jsonBean.getData().getUrl().trim();
                String thirdPart = jsonBean.getData().getPtype().trim();
                if ("1".equalsIgnoreCase(thirdPart)) {
                    Intent intent = new Intent(getContext(), TYFOH5Activity.class);
                    intent.putExtra(TYFOH5Activity.HTML_URL, url);
                    startActivity(intent);
                } else if ("2".equalsIgnoreCase(thirdPart)) {
                    Intent intent = new Intent(getContext(), H5NormalActivity.class);
                    intent.putExtra(H5NormalActivity.EX_HTML, url);
                    intent.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                    intent.putExtra(H5NormalActivity.IS_NEED_TOKEN, false);
                    startActivity(intent);
                } else {
                    String json = jsonBean.getData().getJson().trim();
                    CommodityDetailActivity.StartThis(getActivity(), url, json);
                }
            } else {
                toLogin();
            }
        } else if ("checkmore".equalsIgnoreCase(method)) {
            //更多，去积分商城
            if (UserManager.isLoginS()) {
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "服务"));
                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "更多商品", "", 200, pairs);
                IntegralStoreActivity.startThis(getContext());
            } else {
                toLogin();
            }
        } else if ("otherUrl".equalsIgnoreCase(method)) {
            //其他服务
            String url = jsonBean.getData().getUrl().trim();
            Intent intent = new Intent(getContext(), ServiceH5Activity.class);
            intent.putExtra(EX_HTML, url);
            startActivity(intent);
//            Intent intent = new Intent(getContext(), H5NormalActivity.class);
////            intent.putExtra(EX_TITLE, item.getCommName());
//            intent.putExtra(EX_HTML, url);
//            startActivity(intent);
        }
    }

    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    @OnClick({R.id.load_error})
    public void click(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "服务"));
        switch (view.getId()) {
            case R.id.load_error:
                loadWeb();
                break;

        }
    }

}